package com.njust.diary.filter;

import cn.hutool.core.util.StrUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 服务器默认ISO-8859-1
 * 设置UTF-8
 */

@WebFilter("/*")  //过滤所有资源
public class EncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;
        //处理POST请求
        request.setCharacterEncoding("UTF-8");
        String method =request.getMethod();
        //处理GET请求
        if("GET".equalsIgnoreCase(method)){
            String serverInfo =request.getServletContext().getServerInfo();
            String version=serverInfo.substring(serverInfo.lastIndexOf("/")+1,serverInfo.indexOf("."));
            if(version != null&&Integer.parseInt(version)<8){
                //tomcat7以下
            MyWapper myWapper = new MyWapper(request);
            filterChain.doFilter(myWapper,response);
            return;
            }
        }
filterChain.doFilter(request,response);



    }
    class MyWapper extends HttpServletRequestWrapper{
        private HttpServletRequest request;


        public MyWapper(HttpServletRequest request) {
            super(request);
            this.request=request;
        }

        @Override
        public String getParameter(String name) {
            String value =request.getParameter(name);
            if(StrUtil.isBlank(value)){
                return value;
            }
            try{
                value =new String(value.getBytes("ISO-8859-1"),"UTF-8");
            }catch(Exception e){
                e.printStackTrace();
            }
            return value;
        }
    }
}
